package com.example.jk.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.jk.entity.JUser;
import com.example.jk.service.JUserService;
import com.example.jk.util.Result;
import com.example.jk.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")

public class UserController {
    @Autowired
    JUserService userService;
    @GetMapping("/test")
    public Result test(){
        System.out.println(1/0);
        return new Result(200,"测试查询成功",userService.list());
        //return  userService.list();
    }
    @GetMapping("/selectPage")
    public Result selectPage(JUser user){
        return userService.selectPage(user);
    }

    @PostMapping("/login")
    public Result login(@RequestBody JUser user){
        QueryWrapper<JUser> queryWrapper = new QueryWrapper<JUser>();
        queryWrapper.eq("username",user.getUsername())
                .eq("password",user.getPassword());
        JUser user1 = userService.getOne(queryWrapper);//单个对象查询
        //判断是否有值
        if(user1!=null){
            //登录成功
            String tokenString = new TokenUtil().createToken(user1);
            return  new Result(200,"登录成功",tokenString);
        }else{
            //登录失败
            return  new Result(500,"账号密码有误",null);
        }
    }
    /**
     * 注册接口
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody JUser user){
        return new Result(200,"新增成功",userService.save(user));
    }

    //新增
    @PostMapping("/add")
    public Result add(@RequestBody JUser user){
        boolean bool = userService.save(user);
        return  new Result(200,"新增成功",bool);
    }
    //修改
    @PostMapping("/updata")
    public Result updata(@RequestBody JUser user){
        boolean bool = userService.updateById(user);
        return  new Result(200,"修改成功",bool);
    }

    //删除的接口
    @DeleteMapping("/deleteUser")
    public Result delete(int userId){
        boolean bool  = userService.removeById(userId);
        return  new Result(200,"删除成功",bool);
    }

        @GetMapping("/getId")
        public Result getId(JUser user) {
            try {
                // 调用服务层获取ID
                Integer userId = userService.getUserId(user);

                if (userId != null) {
                    return  new Result(200,"获取ID成功", userId);
                } else {
                    return  new Result(500,"未找到对应用户",null);
                }
            } catch (Exception e) {
                return new Result(500,"获取ID失败",null );
            }
        }

}
